﻿
<button class="btn btn-primary btn-sm" onclick="ShowEdit('')">新建任务</button>
<button class="btn btn-danger btn-sm" onclick="DelTask()">删除</button>
<button class="btn btn-primary btn-sm" hidden="hidden"  onclick="ShowMsg('xx')">查询日志</button>
<div style="height:100%">
    <table id="task_table">
    </table>
</div>


<!--TaskLog Modal -->
<div class="modal fade" id="tasklog" tabindex="-1" aria-labelledby="tasklogLabel">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="tasklogLabel">任务日志</h1>
            </div>
            <div class="modal-body">
                <table id="log_table" style="overflow:auto"></table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!--TaskEdit Modal -->
<div class="modal fade" id="taskEdit" tabindex="-1" aria-labelledby="taskEditLabel">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="taskEditLabel">任务信息</h1>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="form-floating col mb-3">
                        <input type="text" class="form-control" id="taskName" v-model="model.taskName " placeholder="任务名称">
                        <label for="taskName">任务名称</label>
                    </div>
                    <div class="form-floating col mb-3">
                        <input type="text" class="form-control" id="groupName" v-model="model.groupName" placeholder="任务分组">
                        <label for="groupName">任务分组</label>
                    </div>
                </div>

                <div class="form-floating mb-3">
                    <div class="form-floating">
                        <input type="text" class="form-control" id="describe" v-model="model.describe" placeholder="任务描述">
                        <label for="describe">描述</label>
                    </div>
                </div>
                <div class="form-floating mb-3">
                    <div class="form-floating">
                        <input type="text" class="form-control" id="interval" v-model="model.interval" placeholder="间隔">
                        <label for="interval">间隔</label>
                    </div>
                </div>
                <div class="form-floating mb-3">
                    <div class="form-floating">
                        <input type="text" class="form-control" id="apiUrl" v-model="model.apiUrl" placeholder="请求地址">
                        <label for="apiUrl">请求地址</label>
                    </div>
                </div>
                <div class="form-floating mb-3">
                    <div class="form-floating">
                        <select type="text" class="form-control" id="requestType" v-model="model.requestType" placeholder="请求方式">
                        <option value="post">POST</option>
                        <option value="get">GET</option>
                           </select>
                        <label for="requestType">请求方式</label>
                    </div>
                </div>
                <div class="form-floating mb-3">
                    <div class="form-floating">
                        <textarea type="text" style="height: 100px" class="form-control" v-model="model.authKey" id="authKey" placeholder="请求Header"></textarea>
                        <label for="authKey">请求Header</label>
                    </div>
                </div>
                <div class="form-floating mb-3">
                    <div class="form-floating">

                        <textarea type="text" style="height: 100px" class="form-control" v-model="model.apiParams" id="apiParams" placeholder="请求Body"></textarea>
                        <label for="apiParams">请求Body</label>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary"  onclick="SaveData()">保存</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
<div class="toast-container position-fixed bottom-0 end-0 p-3">
    <div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">

        <div class="toast-body">
            {{msg}}
        </div>
    </div>
</div>

<script type="text/javascript">
    let task_table;
    let log_table;
    let LogModal = document.getElementById('tasklog');


    $(document).ready(function () {
        task_table = document.getElementById('task_table');
    })



    
    LogModal.addEventListener('shown.bs.modal', event => {
        console.log('i have show')
    });

   // initLogTable();
    function initLogTable(taskId) {
        $('#log_table').bootstrapTable('destroy');
        $("#log_table").bootstrapTable({
            search: true,
            searchable: true,
            pageSize:10,
            searchHighlight: true,
            pagination: true,
            sidePagination: 'server',
            queryParamsType: 'limit',
            stickyHeader: true,
            locale: "zh-CN",
            virtualScroll: true,
            // fixedColumns: true,
            fixedNumber: 9,
            // method: 'post',
            height: "600",
            contentType: 'application/json',
            queryParams: function(param){
                param.taskId = taskId;
                // taskId: taskId
                return param;
            },
            classes: "table table-striped table-hover table-bordered table-responsive",
            url: "/task/GetJobLogByPage",
            columns: [
                {
                    title: '序号',
                    field: 'no',
                    align: 'center',
                    width: 30,
                    formatter: function (value, row, index) {
                        return index + 1;
                    }
                },
                {
                    sortable: true,
                    searchable: true,
                    title: '开始时间',
                    width: 100,
                    field: 'beginDate'
                },

                {
                    sortable: true,
                    searchable: true,
                    title: '日志内容',
                    width: 150,
                    field: 'msg'
                }
            ]
        });
    }

    $("#task_table").bootstrapTable({
        search: true,
        searchable: true,
        searchHighlight: true,
        pagination: true,
        stickyHeader: true,
        locale: "zh-CN",
        virtualScroll: true,
        fixedColumns: true,
        fixedNumber: 9,
        classes: "table table-striped table-hover table-bordered table- responsive",
        url: "/task/GetJobs",
        columns: [
            {
                checkbox:true,
            },
            {
                title: '序号',
                field: 'no',
                align: 'center',
                width: 100,
                formatter: function (value, row, index) {
                    // var pageSize = $('#task_table').bootstrapTable('getOptions').pageSize;     //通过table的#id 得到每页多少条
                    // var pageNumber = $('#task_table').bootstrapTable('getOptions').pageNumber; //通过table的#id 得到当前第几页
                    // return pageSize * (pageNumber - 1) + index + 1;    // 返回每条的序号： 每页条数 *（当前页 - 1 ）+ 序号
                    return index + 1;
                }
            },
            {
                sortable: true,
                searchable: true,
                title: '作业名称',
                width: 120,
                field: 'taskName'
            },
            {
                sortable: true,
                searchable: true,
                title: '分组',
                width: 60,
                field: 'groupName'
            }, {
                title: '描述',
                width: 240,
                searchable: true,
                field: 'describe'
            },

            {
                title: '间隔',
                width: 180,
                field: 'interval'
            }, {
                title: '状态',
                width: 80,
                field: 'status',
                formatter: StatusFormat
            }, {
                title: '请求地址',
                searchable: true,
                width: 240,
                field: 'apiUrl'
            }, {
                title: '请求方式',
                searchable: true,
                width: 50,
                field: 'requestType'
            }, {
                title: '开始时间',
                width: 240,
                visible: true,
                field: 'startTime'
            }, {
                title: '操作',
                field: 'id',
                width: 240,
                formatter: function (value, row, index) {
                    var status = row.status;
                    var st_tx = '';
                    if (status != '0') {
                        st_tx = '启动';
                    } else {
                        st_tx = '停止';
                    }
                    var html_str = "<button class='btn btn-outline-primary btn-sm'   OnClick='ShowEdit(" +
                    JSON.stringify(row) + ")'  style='margin-right:8px;'>编辑 </button>";
                   
                    html_str += "<button class='btn btn-outline-primary btn-sm' style='margin-right:8px;' OnClick='TriggerJob(" +
                        JSON.stringify(row) + ")'  >"+st_tx+" </button>";
                    html_str += "<button class='btn btn-outline-danger btn-sm' style='margin-right:8px;' OnClick='RunJob(" +
                        JSON.stringify(row) + ")' >立即执行 </button>";
                    html_str += "<button class='btn btn-outline-secondary btn-sm' OnClick=\"ShowLog('" + value + "\')\"  style='margin-right:8px;'>日志 </button>";
                    return html_str;
                }
            }
        ]
    })

    var app_toast = new Vue({
        el: '#liveToast',
        data: {
            msg:'hello world'
        }
    });
    var app = new Vue({
        el: "#taskEdit",
        data: {
            model: {},
            cmd: "",
        }
    });
    //批量删除
    function DelTask() {
        var chk_data = $("#task_table").bootstrapTable('getSelections');
        if (chk_data.length == 0) {
            layer.msg('请先选择要删除的任务！');
            return;
        }
        console.log(chk_data);
        layer.confirm('确定删除当前选中任务？', {
            btn: ['确定', '取消'] //按钮
        }, function () {
            axios({
                method: 'post',
                url: '/task/BatchRemove',
                data: chk_data,
                headers: { 'Content-Type': 'application/json;charset=UTF-8' }
            }).then(function (res) {


                $("#task_table").bootstrapTable('refresh');
                if (res.data != null) {
                    layer.msg(res.data.msg);
                }
            }).catch(function (err) {
                console.log(err);
                if (err.response.status === 401) {
                    return window.location.href = '/home/index';
                }

            });
        }, function () {
            
        });


    }

    function StatusFormat(st, row, idx) {
        var text = "";
        var background = "";
        switch (st) {
            case 0:
                background = '#9eff9e';
                text = '正常';
                break;
            case 1:
                background = '#acdeff';
                text = '暂停';
                break;
            case 2:
                background = '#fc2f2f';
                text = '完成';
                break;
            case 3:
                background = '#607D8B';
                text = '异常';
                break;
            case 4:
                background = '#607D8B';
                text = '阻塞';
                break;
            case 5:
                background = '#e7e7e7';
                text = '停止';
                break;
            default:
                background = '#e7e7e7';
                text = '不存在';
                break;
        }
        var html_str = "<div style='background-color:" + background + ";text-align:center'>" + text + "</span>";
        return html_str;
    }

    function ShowLog(taskId) {
        var opt = {
            backdrop: true,
            focus: true,
            keyboard: true,
        }
        console.log('showlog' + taskId);

        const MyLogModal = new bootstrap.Modal(LogModal, opt);
        MyLogModal.show();

        initLogTable(taskId);

    }
    
    let Edit_Modal = new bootstrap.Modal(document.getElementById('taskEdit'), {
        backdrop: true,
        focus: true,
        keyboard: true,
    });
    function ShowEdit(rw) {

        app.model = rw;
        console.log(app.model);
        // console.log(rw);


        Edit_Modal.show();

    }

    function RunJob(job) {
        axios({
            method: 'post',
            url: '/task/Run',
            data: job,
            headers: { 'Content-Type': 'application/json;charset=UTF-8' }
        }).then(function (res) {
 
 
            if (res.data.status) {
 
                $("#task_table").bootstrapTable('refresh');
            }
            layer.msg(res.data.msg);

        }).catch(function (err) {
            console.log(err);
            if (err.response.status === 401) {
                return window.location.href = '/home/index';
            }

        });
    }

    function TriggerJob(job) {

        axios({
            method: 'post',
            url: '/task/SwitchJob',
            data: job,
            headers: { 'Content-Type': 'application/json;charset=UTF-8' }
        }).then(function (res) {
            // fun && fun(response.data);

            console.log(res);
            if (res.data.status) {
  
                $("#task_table").bootstrapTable('refresh');
            }
            layer.msg(res.data.msg);

        }).catch(function (err) {
            console.log(err);
            if (err.response.status === 401) {
                return window.location.href = '/home/index';
            }

        });
    }

    function ShowMsg(msg) {
        app_toast.msg = msg;
        console.log(msg)
        const liveToast = bootstrap.Toast.getOrCreateInstance(document.getElementById('liveToast'));
        liveToast.show();
    }

    function SaveData() {
        var params = app.model;

        axios({
            method: 'post',
            url: '/task/SaveJob',
            data: params,
            headers: { 'Content-Type': 'application/json;charset=UTF-8' }
        }).then(function (res) {
            // fun && fun(response.data);

            console.log(res);
            if (res.data.status) {
                Edit_Modal.hide();
                $("#task_table").bootstrapTable('refresh');
            }
 
            layer.msg(res.data.msg);
         
        }).catch(function (err) {
            console.log(err);
            if (err.response.status === 401) {
                return window.location.href = '/home/index';
            }
       
        });
    }
</script>